package com.haoshuang.zhouzhoubang.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer

import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityAppointmentCustomerBinding
import com.haoshuang.zhouzhoubang.model.bean.OrderDetail2Bean
import com.haoshuang.zhouzhoubang.model.bean.RenWuBean
import com.haoshuang.zhouzhoubang.model.bean.TimeBean8
import com.haoshuang.zhouzhoubang.model.bean.YyBean
import com.haoshuang.zhouzhoubang.model.event.TransferOrderSuccess
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tx3Dialog
import com.haoshuang.zhouzhoubang.ui.page.order.assignment.TaskAssignmentActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.team.TeamListAdapter
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.haoshuang.zhouzhoubang.ui.vm.AppointmentCustomerViewModel
import com.jeremyliao.liveeventbus.LiveEventBus

import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.ktx.fromJson
import com.mufeng.libs.utils.ktx.fromJsonToList
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible

import java.text.DecimalFormat


/**
 * 个人预约客户
 */
class AppointmentCustomerActivity :
    BaseVMActivity<AppointmentCustomerViewModel, ActivityAppointmentCustomerBinding>() {

    override fun initView(savedInstanceState: Bundle?) {
        binding.appBar.ivBack.click { finish() }
        binding.appBar.tvTitle.text = "预约客户"
    }

    private var yyBean: YyBean? = null

    /// 订单详情
    private var orderDetailBean: OrderDetail2Bean? = null
    var list = arrayListOf<TimeBean8.Timer>()
    var list2 = arrayListOf<TimeBean8>()
    var service_day = ""
    var service_time = ""
    var user_status = ""

    var ids = 0
    var gson = Gson()
    lateinit var adapter3: TeamListAdapter
    var list3 = arrayListOf<YyBean.ThirdInfo.TeamUser>()
    var list6 = arrayListOf<YyBean.ThirdInfo.TeamUser>()
    var user_id9 = ""
    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        ids = intent.getIntExtra("ids", 0)

        XPopup.Builder(this).asCustom(Tx3Dialog(this) {}).show()
        binding.apply {
            val lay = LinearLayoutManager(this@AppointmentCustomerActivity)
            lay.orientation = LinearLayoutManager.HORIZONTAL

            val lay2 = LinearLayoutManager(this@AppointmentCustomerActivity)
            lay2.orientation = LinearLayoutManager.HORIZONTAL
            rvList3.layoutManager = lay2

            adapter3 = TeamListAdapter(list3)
            rvList3.adapter = adapter3
            llAdd.clickWithTrigger {
                var str = gson.toJson(list6)
                startPageForResult<TaskAssignmentActivity>(
                    "ids" to ids.toString(), "user_id9" to user_id9, "bean" to str, "isPersonal" to true
                ){code, data ->
                    if (code == 200 && data != null){
//                        vm.getConfirmOrderTime("id" to ids)
                        val leader = data.getString("member").fromJson<RenWuBean.TeamMemberData>()
                        val members = data.getString("members").fromJsonToList<RenWuBean.TeamMemberData>()
                        tvAdd.load(leader.avatar, R.mipmap.rl)
                        list3.clear()
                        list3.addAll(members.map { YyBean.ThirdInfo.TeamUser(
                            order_id = "",
                            user_id = it.to_user_id.toString(),
                            nickname = it.nickname,
                            avatar = it.avatar,
                            phone = ""
                        ) })
                        adapter3.notifyDataSetChanged()
                    }
                }
            }
            adapter3.setOnItemChildClick(id = R.id.callPhone){ view, position, item ->
                if (item == null) return@setOnItemChildClick
                if (list3[position].phone.isNullOrBlank()) {
                    toast("电话不能为空")
                } else {
                    callPhone(list3[position].phone)
                }
            }
            adapter3.setOnItemChildClick(id = R.id.tvAdd){ view, position, item ->
                if (item == null) return@setOnItemChildClick
                var str = gson.toJson(list6)
                startPageForResult<TaskAssignmentActivity>(
                    "ids" to ids.toString(), "user_id9" to user_id9, "bean" to str, "isPersonal" to true
                ){code, data ->
                    if (code == 200 && data != null){
                        val leader = data.getString("member").fromJson<RenWuBean.TeamMemberData>()
                        val members = data.getString("members").fromJsonToList<RenWuBean.TeamMemberData>()
                        tvAdd.load(leader.avatar, R.mipmap.rl)
                        list3.clear()
                        list3.addAll(members.map { YyBean.ThirdInfo.TeamUser(
                            order_id = "",
                            user_id = it.to_user_id.toString(),
                            nickname = it.nickname,
                            avatar = it.avatar,
                            phone = ""
                        ) })
                        adapter3.notifyDataSetChanged()
                    }
                }
            }

            callPhone.clickWithTrigger {
                if (user_phone.isNullOrBlank()) {
                    toast("电话不能为空")
                    return@clickWithTrigger
                }
                callPhone(user_phone)
            }
            tvCommit.clickWithTrigger {
                if (service_day.isNullOrBlank()) {
                    vm.getData3("id" to ids)
                } else {

                    vm.getData3(
                        "id" to ids,
                        "service_day" to service_day,
                        "service_time" to service_time
                    )
                }

            }
            callPhone2.clickWithTrigger {
                if (user_phone2.isNullOrBlank()) {
                    toast("电话不能为空")
                    return@clickWithTrigger
                }
                callPhone(user_phone2)
            }
            tvUpdateTime.clickWithTrigger {
                startPageForResult<UpdateServiceTimeActivity>("cate_id" to cate_id){code, data ->
                    if (code == Activity.RESULT_OK){
                        if (data != null) {
                            service_day = data.getStringExtra("service_day").toString()
                            val service_day1 = data.getStringExtra("service_day1")
                            service_time = data.getStringExtra("service_time").toString()
                            binding.tvTime.text = "$service_day1     $service_time"
                        }
                    }
                }
            }




        }
//        binding.llAdd.clickWithTrigger {
//            startPageForResult<AppointMemberActivity>("id" to ids.toString()){code, data ->
//                if (code == 200 && data != null){
//                    val item = data.getParcelableExtra("chooseMember") as TeamMemberBean.TeamMemberData?
//                    binding.tvAdd.load(item?.avatar)
//                }
//            }
//        }

        binding.llTransferOrder.clickWithTrigger {
            val content = if (orderDetailBean?.remaining_transfer_orders_num == "0") {
                "您本月转单已用完，\n转出后将扣除${orderDetailBean?.transfer_orders_deduct_point}个服务积分"
            } else {
                "您是否将本单转出\n转出后将不再服务次单"
            }
            XPopup.Builder(this)
                .asCustom(ConfirmDialog(
                    this,
                    title = "温馨提示",
                    content,
                    cancelStr = "再考虑考虑",
                    confirmStr = "确认转出",
                ) {
                    vm.transferOrder("id" to ids)
                })
                .show()
        }

        vm.getConfirmOrderTime("id" to ids)
    }

    override fun onResume() {
        super.onResume()
        vm.getOrderDetail("id" to ids)
        vm.getConfirmOrderTime("id" to ids)
    }

    var user_phone = ""
    var user_phone2 = ""
    var cate_id = ""

    @SuppressLint("NotifyDataSetChanged")
    override fun startObserve() {
        // 转单
        vm.transferOrderData.observeState(this){
            onLoading {showLoading()}
            onError {code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                LiveEventBus.get(TransferOrderSuccess::class.java).post(TransferOrderSuccess(ids))
                finish()
            }
        }
        vm.getOrderDetailData.observeState(this) {
            onLoading { }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                orderDetailBean = it
                if (it?.remaining_transfer_orders_num == "0") {
                    binding.tvTransferOrderNum.text = "(本月转单已用完)"
                } else {
                    binding.tvTransferOrderNum.text =
                        "(本月剩余${it?.remaining_transfer_orders_num}次转单)"
                }

            }
        }
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("确认成功")
                LiveEventBus.get<Boolean>("Sxx6").post(true)
                finish()
            }
        }

        vm.getConfirmOrderTimeData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                yyBean = it
                if (it != null) {
                    try {
                        if (it.second_info.size > 0) {
                            list2.clear()
                            list2.addAll(it.second_info.toMutableList())
                            list2[0].isCheck = 1
                            list = list2[0].timer
                            service_day = list2[0].date_timestamp


                        }
                    } catch (e: Exception) {

                    }

                    binding.apply {
                        if (it.third_info.user_status == "1") {
                            tvAdd.visible()
                        } else {
                            tvAdd.gone()
                        }
                        realName.text = it.first_info.real_name
                        storeName.text = it.first_info.store_name
                        serviceTime.text = it.first_info.service_time
                        baseAddress.text = it.first_info.base_address
                        user_phone = it.first_info.user_real_phone
                        cate_id = it.first_info.cate_id
                        if (it.third_info.team_member.isNotEmpty()) {
                            list3.clear()
                            list6.clear()
                            list3.addAll(it.third_info.team_member)
                            list6.addAll(it.third_info.team_member)
                            adapter3.notifyDataSetChanged()
                        }else{
                            list3.clear()
                            list3.add(YyBean.ThirdInfo.TeamUser("", "", "", "", ""))
                            adapter3.notifyDataSetChanged()
                        }
                        if (it.third_info.team_leader.nickname.isNotEmpty()) {
                            tvAdd.load(it.third_info.team_leader.avatar, R.mipmap.rl)
                            user_phone2 = it.third_info.team_leader.phone
                            user_id9 = it.third_info.team_leader.user_id
                            callPhone2.visible()
                        } else {
                            callPhone2.gone()
                        }
                        if (it.confirm_time.is_residuetime == 1) {
                            residueTime.text = "已超时"
                            residueTime.setTextColor(Color.parseColor("#F53131"))
                        } else {
                            val countDownTimer: CountDownTimer =
                                object :
                                    CountDownTimer(it.confirm_time.residue_time * 1000, 1 * 1000) {
                                    @SuppressLint("SimpleDateFormat")
                                    override fun onTick(millisUntilFinished: Long) {
                                        val s: String = formatDateTime(millisUntilFinished)
                                        //                Log.e("wy", "sysTimeStr s: "+s );
                                        residueTime.setText(s)

                                        residueTime.setTextColor(Color.parseColor("#00B7F5"))
                                    }

                                    override fun onFinish() {
                                        residueTime.setText("已超时")
                                        residueTime.setTextColor(Color.parseColor("#F53131"))
                                    }
                                }
                            countDownTimer.start()
                        }
                    }
                }
            }
        }
    }

    fun formatDateTime(milliseconds: Long): String {
        val sb = StringBuilder()
        val mss = milliseconds / 1000
        val days = mss / (60 * 60 * 24)
        val hours = mss % (60 * 60 * 24) / (60 * 60)
        val minutes = mss % (60 * 60) / 60
        val seconds = mss % 60
        val format = DecimalFormat("00")

        if (days > 0 || hours > 0) {
            sb.append(format.format(hours)).append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        } else {
            sb.append("00").append(":").append(format.format(minutes)).append(":")
                .append(format.format(seconds))
        }
        return sb.toString()
    }
}